﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Volo.Abp;
using Volo.Abp.Auditing;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Guids;

namespace Demo.OrderManager.Orders;

/// <summary>
/// 订单聚合根
/// </summary>
public class Order : AggregateRoot<Guid>, IHasCreationTime
{
    /// <summary>
    /// 参考号
    /// </summary>
    public virtual string ReferenceNo { get; protected set; }

    /// <summary>
    /// 总数量
    /// </summary>
    public virtual int TotalItemCount { get; protected set; }

    /// <summary>
    /// 创建时间
    /// </summary>
    public virtual DateTime CreationTime { get; protected set; }

    /// <summary>
    /// 订单商品列表
    /// </summary>
    public virtual List<OrderLine> OrderLines { get; protected set; }

    protected Order()
    {

    }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="id">订单编号</param>
    /// <param name="referenceNo">参考号</param>
    public Order(Guid id, string referenceNo)
    {
        Check.NotNull(referenceNo, nameof(referenceNo));

        Id = id;
        ReferenceNo = referenceNo;

        OrderLines = new List<OrderLine>();
    }

    /// <summary>
    /// 添加产品
    /// </summary>
    /// <param name="productId">产品ID</param>
    /// <param name="count">数量</param>
    public void AddProduct(Guid productId, int count)
    {
        if (count <= 0)
        {
            throw new ArgumentException(
                "You can not add zero or negative count of products!",
                nameof(count)
            );
        }

        var existingLine = OrderLines.FirstOrDefault(ol => ol.ProductId == productId);

        if (existingLine == null)
        {
            OrderLines.Add(new OrderLine(this.Id, productId, count));
        }
        else
        {
            existingLine.ChangeCount(existingLine.Count + count);
        }

        TotalItemCount += count;
    }
}